#include "mainwindow.h"
#include "./ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 监听套接字，指定父对象，让其自动回收空间
    tcpServer = new QTcpServer(this);
    tcpServer->listen(QHostAddress::Any, 9999);

    setWindowTitle("服务器：8888");

    connect(tcpServer, &QTcpServer::newConnection,
        [=]()
        {
            // 取出建立好连接的套接字
            tcpSocket = tcpServer->nextPendingConnection();

            // 获取对方IP和端口
            QString ip = tcpSocket->peerAddress().toString();
            qint16 port = tcpSocket->peerPort();
            QString tmp = QString("[%1:%2]:成功连接").arg(ip).arg(port);
            qDebug()<<tmp;

            clientList.push_back(tcpSocket);

            // 读数据
            connect(tcpSocket, &QTcpSocket::readyRead,
                    [=]()
                    {                        
                        for (auto socket : clientList)
                        {                            
                            QByteArray array = socket->readAll();
                            if (array.size() > 0)
                            {
                                qDebug()<<array;
                                for ( auto sendSocket : clientList)
                                {
                                    if (socket != sendSocket)
                                    {
                                        sendSocket->write(array);
                                        qDebug()<<"write --- ";
                                    }
                                }
                            }

                        }                        
                    }
                    );

            // 连接断开
            connect(tcpSocket, &QTcpSocket::disconnected,
                    [=]()
                    {
                        for(int i=0; i<clientList.size(); i++)
                        {
                            if(clientList[i]->state() == QAbstractSocket::UnconnectedState)
                            {
                                clientList.removeAt(i);
                                break;
                            }
                        }
                    }
                    );
        }

        );
}

MainWindow::~MainWindow()
{
    delete ui;
}

